/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.utils
{
	import com.puny.mvc.models.Model;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;

	public class EnhancedEventDispatcher extends EventDispatcher
	{
		private var _listeners:Array = new Array();

		public function EnhancedEventDispatcher(target:IEventDispatcher=null)
		{
			super(target);
		}

		override public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void {
			var model:Model = new Model();
			model.type = type;
			model.listener = listener;
			_listeners.push(model);
			super.addEventListener(type,listener,useCapture,priority,useWeakReference);
		}

		override public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void {
			var length:int = _listeners.length;
			for (var index:int = 0;index < length;index++) {
				var model:Model = _listeners[index];
				if (model.type == type && model.listener == listener) {
					model.type = null;
					model.listener = null;
					_listeners.splice(index,1);
					break;
				}
			}
			super.removeEventListener(type,listener,useCapture);
		}

		/**
		 * Faster dispatchEvent
		 * @param event
		 */
		override public function dispatchEvent(evt:Event):Boolean {
		 	if (hasEventListener(evt.type) || evt.bubbles) {
		  		return super.dispatchEvent(evt);
		  	}
		 	return true;
		}		

		public function cleanUp():void {
			removeAllListeners();
		}
		private function removeAllListeners():void {
			while(_listeners.length > 0) {
				var model:Model = _listeners.pop();
				super.removeEventListener(model.type,model.listener);
				model.type = null;
				model.listener = null;
			}
		}
		
	}
}